package com.kr.aia.powerrp.common;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.kr.aia.powerrp.R;

import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

public class RecControllerThread extends SurfaceView implements SurfaceHolder.Callback {

	private Camera mCamera = null;
	private MediaRecorder mrec;
	private SurfaceHolder surfaceHolder;
	private String dataPath;
	private String dirName;
	
	RecThread rThread;

	public RecControllerThread(Context context, String dirname) {
		super(context);
		
		this.dirName = dirname;
		this.dataPath = Environment.getExternalStorageDirectory().getPath() + "/powerRP/" + dirName;
		initDirectories();

		surfaceHolder = getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
		rThread = new RecThread();
	}
	
    private void startCamera(SurfaceHolder sh, int width, int height) {
        Camera.Parameters p = mCamera.getParameters();
        
        // Camera.Size s = p.getSupportedPreviewSizes().get(0);
        p.setPreviewSize(width, height);

        mCamera.setParameters(p);

        try {
        	mCamera.setPreviewDisplay(sh);
        } catch (Exception e) {
        }
        
        mCamera.startPreview();
    }
    
    public void startRecording() throws IOException 
    {
    	if(checkSDMount()){
    		
    		
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String currentDate = sdf.format(new Date());
    		
            String fileName = currentDate+".mp4";
            
            
	    	mCamera.unlock();
	    	
	    	mrec = new MediaRecorder();  // Works well
	        mrec.setCamera(mCamera);
	
	        mrec.setPreviewDisplay(surfaceHolder.getSurface());
	        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
	        mrec.setAudioSource(MediaRecorder.AudioSource.MIC); 
	
	        mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
	        mrec.setPreviewDisplay(surfaceHolder.getSurface());
	        mrec.setOutputFile(this.dataPath + "/" + fileName);
	        //Log.i(getResources().getString(R.string.app_name), this.dataPath + "/" + fileName );
	        
	    	mrec.prepare();
	        mrec.start();
    	}
    }

    public void stopRecording() {
        mrec.stop();
        //mrec.reset();
        mrec.release();
        mrec = null;
    }
    
    public void releaseMediaRecorder(){
        if (mrec != null) {
            mrec.reset();   // clear recorder configuration
            mrec.release(); // release the recorder object
            mrec = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    public void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
		//startCamera(holder, width, height);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		
		
		rThread.run();
    	
        
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mCamera.stopPreview();
        mCamera.release();
	}
	
	public void initDirectories(){
		
		if(checkSDMount()){
			File dir = new File(dataPath);
			if(!dir.exists()) {
				dir.mkdirs();
			}
		}
		//Log.i("PRP", path);
	}
	
	public boolean checkSDMount(){
		Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		if(isSDPresent){
			//Toast toast = Toast.makeText(getContext(), "SD카드가 삽입 되었습니다.", Toast.LENGTH_SHORT); 
			//toast.show();
			return true;
		}else{
			Toast toast = Toast.makeText(getContext(), "SD카드가 삽입되지 않았습니다.", Toast.LENGTH_SHORT); 
			toast.show();
			return false;
		}
	}
	
	
	class RecThread extends Thread{
		
		public RecThread(){
			Camera.CameraInfo camInfo = new Camera.CameraInfo();
			int camCount = 0;
			camCount = Camera.getNumberOfCameras();
			for(int camIdx = 0 ; camIdx < camCount; camIdx++){
				Camera.getCameraInfo(camIdx, camInfo);
				if( camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
					try{
						mCamera = Camera.open(camIdx);
					}catch(RuntimeException e){
						e.printStackTrace();
					}
				}
			}
		}
		
		
		public void run(){
			
			try {
	        	mCamera.setPreviewDisplay(surfaceHolder);
	        	startCamera(surfaceHolder, 480, 360);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
		}
	}
	
	
	
	
}
